package com.xmy.framework.web.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.xmy.common.core.domain.entity.SysUser;
import com.xmy.common.core.domain.entity.WeChatUser;
import com.xmy.common.core.domain.model.LoginUser;
import com.xmy.common.exception.ServiceException;
import com.xmy.common.utils.DateUtils;
import com.xmy.common.utils.http.HttpUtils;
import com.xmy.common.utils.ip.IpUtils;
import com.xmy.common.utils.uuid.UUID;
import com.xmy.framework.pojo.dos.WeChatSecret;
import com.xmy.framework.pojo.dos.WxMiniAppLoginResponseDO;
import com.xmy.system.service.ISysWeChatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class WxLoginService {
    @Autowired
    private WeChatSecret weChatSecret;
    @Autowired
    private ISysWeChatUserService iWeChatUserService;
    @Autowired
    private UserDetailsServiceImpl UserDetailsService;
    @Autowired
    private TokenService tokenService;

    /**
     * 小程序一键登录
     *
     * @return token
     */
    public String miniProgramLogin(String code) {
        //微信小程序获取openId请求地址
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", weChatSecret.getAppId()).replace("{1}", weChatSecret.getAppSecret()).replace("{2}", code);
        String res = HttpUtils.sendGet(replaceUrl);
        WxMiniAppLoginResponseDO response = JSONUtil.toBean(res, WxMiniAppLoginResponseDO.class);
        if (StrUtil.isEmpty(response.getErrcode())) {
            //检查数据库种是否有个openId对应的用户，若有，则直接返回token，若没有，则创建用户后再生成token并返回
            WeChatUser user = iWeChatUserService.getUserByOpenId(response.getOpenid());
            if (user == null) {
                WeChatUser regUser = new WeChatUser();
                regUser.setOpenid(response.getOpenid());
                regUser.setSessionKey(response.getSessionKey());
                regUser.setUserName("微信用户_" + UUID.fastUUID());
                regUser.setNickname(regUser.getUserName());
                user = regUser;
                iWeChatUserService.registerUser(user);
            }
//            UserDetails userDetail = UserDetailsService.createLoginUser(user);
//            LoginUser loginUser = BeanUtil.copyProperties(userDetail, LoginUser.class);
//            LoginUser loginUser = UserDetailsService.createLoginUser(user);
            LoginUser loginUser = new LoginUser(user);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(response.getOpenid(), response.getSessionKey());
            authenticationToken.setDetails(loginUser);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //记录登录日志
            recordLoginInfo(loginUser.getUserId());
            // 生成token
            return tokenService.createToken(loginUser);
        } else {
            throw new ServiceException(StrUtil.format("获取微信授权信息失败，错误编码{}，错误信息：{}", response.getErrcode(), response.getErrmsg()));
        }
    }
    public void recordLoginInfo(Long userId)
    {

        WeChatUser weChatUser = new WeChatUser ();
        weChatUser.setId(userId);
        weChatUser.setLoginDate(DateUtils.getNowDate());
        iWeChatUserService.updateUser(weChatUser);
    }
}
